package hu.szyrt.bug.adapters;

import hu.szyrt.bug.R;
import hu.szyrt.bug.models.PlaceItemBase;
import hu.szyrt.bug.utils.Assets;
import hu.szyrt.bug.views.PlaceImageView;

import java.util.ArrayList;
import java.util.List;

import android.graphics.drawable.BitmapDrawable;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PlacesListAdapter extends BaseAdapter{

	private List<PlaceItemBase> items = new ArrayList<PlaceItemBase>();
	private ViewHolder holder;
	private Assets assets;
	private String terms;
	
	public PlacesListAdapter(Assets assets, List<PlaceItemBase> items) {
		this.assets = assets;
		this.items = items;			
	}
	
	public void changeList(List<PlaceItemBase> items){
		this.items = items;
		notifyDataSetChanged();
	}
	
	public void setTerms(String terms) {
		this.terms = terms;
	}
	
	@Override
	public int getCount() { return items.size(); }
	@Override
	public Object getItem(int position) {return items.get(position);}
	@Override
	public long getItemId(int position) { return position; }
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		PlaceItemBase item = items.get(position);
		
		if(convertView == null){
			convertView = View.inflate(parent.getContext(), R.layout.category_list_item, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView.findViewById(R.id.title);
			holder.content = (TextView) convertView.findViewById(R.id.content);
			holder.polaroid = (PlaceImageView) convertView.findViewById(R.id.polaroid);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder)convertView.getTag();
		}
		
		if(terms == null || terms.length() == 0){
			holder.title.setText(item.getName());
			holder.content.setText(item.getDescription());
		}else{
			holder.title.setText(Html.fromHtml(item.getName().replaceAll("(?i)"+terms, "<font color='red'>" + terms + "</font>")));
			holder.content.setText(Html.fromHtml(item.getDescription().replaceAll("(?i)"+terms, "<font color='red'>" + terms + "</font>")));
		}		
	
		if(holder.polaroid.getDrawable() != null && ((BitmapDrawable)holder.polaroid.getDrawable()).getBitmap() != null)
			((BitmapDrawable)holder.polaroid.getDrawable()).getBitmap().recycle();
		holder.polaroid.setImageBitmap(assets.loadPolaroid(item.getImagePolaroid(), 3));
		
		holder.polaroid.setStampImage1(item.getHighlighstNumber() > 0 ? assets.loadCategoryIcon("highlights.png", 2) : null);
		holder.polaroid.setStampImage2(item.hasDiscount() ? assets.loadCategoryIcon("deals.png", 2) : null);
		
		return convertView;
	}
	
	static class ViewHolder{
		TextView title, content;
		PlaceImageView polaroid;
	}
	
}
